home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / HISTORY.PY < prev    next >
Encoding:
Python Source  |  2000-07-26  |  10.8 KB  |  314 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. """Object Histories"""
  65.  
  66. __version__='$Revision: 1.1.14.4 $'[11:-2]
  67.  
  68. import Globals, ndiff, ExtensionClass
  69. from DateTime import DateTime
  70. from Acquisition import Implicit
  71. from string import join, split, atoi, strip
  72. from struct import pack, unpack
  73. from DocumentTemplate.DT_Util import html_quote
  74.  
  75. class TemporalParadox(Exception): pass
  76.  
  77. class HistorySelectionError(Exception): pass
  78.  
  79. class HystoryJar:
  80.     """A ZODB Connection-like object that provides access to data
  81.     but prevents history from being changed."""
  82.  
  83.     def __init__(self, base):
  84.         self.__base__=base
  85.  
  86.     def __getattr__(self, name):
  87.         return getattr(self.__base__, name)
  88.  
  89.     def commit(*args, **kw):
  90.         raise TemporalParadox, "You can\'t change history!"
  91.  
  92.     tpc_begin = tpc_finish = commit
  93.  
  94.     def abort(*args, **kw): pass
  95.  
  96. def historicalRevision(self, serial):
  97.     state=self._p_jar.oldstate(self, serial)
  98.     rev=self.__class__.__basicnew__()
  99.     rev._p_jar=HystoryJar(self._p_jar)
  100.     rev._p_oid=self._p_oid
  101.     rev._p_serial=serial
  102.     rev.__setstate__(state)
  103.     rev._p_changed=0
  104.     return rev
  105.  
  106. class Historian(Implicit):
  107.     """An Historian\'s job is to find hysterical revisions of
  108.     objects, given a time."""
  109.  
  110.     def __getitem__(self, key):
  111.         self=self.aq_parent
  112.  
  113.         serial=apply(pack, ('>HHHH',)+tuple(map(atoi, split(key,'.'))))
  114.  
  115.         if serial == self._p_serial: return self
  116.  
  117.         rev=historicalRevision(self, serial)
  118.  
  119.         return rev.__of__(self.aq_parent)
  120.  
  121.     def manage_workspace(self, REQUEST):
  122.         "We aren\'t real, so we delegate to that that spawned us!"
  123.         raise 'Redirect', REQUEST['URL2']+'/manage_change_history_page'
  124.  
  125. class Historical(ExtensionClass.Base):
  126.     """Mix-in class to provide a veiw that shows hystorical changes
  127.  
  128.     The display is similar to that used for undo, except that the transactions
  129.     are limited to those that effect the displayed object and that the
  130.     interface doesn't provide an undo capability.
  131.  
  132.     This interface is generally *only* interesting for objects, such
  133.     as methods, and documents, that are self-contained, meaning that
  134.     they don't have persistent sub-objects.
  135.     """
  136.  
  137.     HistoricalRevisions=Historian()
  138.  
  139.     __ac_permissions__=(
  140.         ('View History',
  141.          ('manage_change_history_page','manage_change_history',
  142.           'manage_historyCompare', 'manage_historicalComparison',
  143.           )
  144.          ),
  145.         )
  146.     
  147.     manage_options=({'label':'History', 'action':'manage_change_history_page',
  148.                      'help':('OFSP','History.stx')
  149.                      },
  150.                    )
  151.  
  152.     manage_change_history_page=Globals.HTMLFile(
  153.         'history', globals(),
  154.         HistoryBatchSize=20,
  155.         first_transaction=0, last_transaction=20)
  156.  
  157.     def manage_change_history(self):
  158.         first=0
  159.         last=20
  160.         request=getattr(self, 'REQUEST', None)
  161.         if request is not None:
  162.             first=request.get('first_transaction', first)
  163.             last=request.get('last_transaction',last)
  164.         
  165.  
  166.         r=self._p_jar.db().history(self._p_oid, None, last)
  167.         r=r[first:]
  168.  
  169.         for d in r:
  170.             d['time']=DateTime(d['time'])
  171.             d['key']=join(map(str, unpack(">HHHH", d['serial'])),'.')
  172.  
  173.         return r
  174.  
  175.     def manage_beforeHistoryCopy(self): pass # ? (Hook)
  176.  
  177.     def manage_historyCopy(self, keys=[], RESPONSE=None, URL1=None):
  178.         "Copy a selected revision to the present"
  179.         if not keys:
  180.             raise HistorySelectionError, (
  181.                 "No historical revision was selected.<p>")
  182.  
  183.         if len(keys) > 1:
  184.             raise HistorySelectionError, (
  185.                 "Only one historical revision can be "
  186.                 "copied to the present.<p>")
  187.  
  188.         key=keys[0]
  189.         serial=apply(pack, ('>HHHH',)+tuple(map(atoi, split(key,'.'))))
  190.  
  191.         if serial != self._p_serial:
  192.             self.manage_beforeHistoryCopy()
  193.             state=self._p_jar.oldstate(self, serial)
  194.             self.__setstate__(state)
  195.             self._p_changed=1
  196.             self.manage_afterHistoryCopy()
  197.  
  198.         if RESPONSE is not None and URL1 is not None:
  199.             RESPONSE.redirect(URL1+'/manage_workspace')
  200.  
  201.     def manage_afterHistoryCopy(self): pass # ? (Hook)
  202.  
  203.     
  204.     _manage_historyComparePage=Globals.HTMLFile(
  205.         'historyCompare', globals(), management_view='History')
  206.     def manage_historyCompare(self, rev1, rev2, REQUEST,
  207.                               historyComparisonResults=''):
  208.         dt1=DateTime(rev1._p_mtime)
  209.         dt2=DateTime(rev2._p_mtime)
  210.         return self._manage_historyComparePage(
  211.             self, REQUEST,
  212.             dt1=dt1, dt2=dt2,
  213.             historyComparisonResults=historyComparisonResults)
  214.  
  215.     def manage_historicalComparison(self, REQUEST, keys=[]):
  216.         "Compare two selected revisions"
  217.         if not keys:
  218.             raise HistorySelectionError, (
  219.                 "No historical revision was selected.<p>")
  220.         if len(keys) > 2:
  221.             raise HistorySelectionError, (
  222.                 "Only two historical revision can be compared<p>")
  223.         
  224.         serial=apply(pack, ('>HHHH',)+tuple(map(atoi, split(keys[-1],'.'))))
  225.         rev1=historicalRevision(self, serial)
  226.         
  227.         if len(keys)==2:
  228.             serial=apply(pack,
  229.                          ('>HHHH',)+tuple(map(atoi, split(keys[0],'.'))))
  230.  
  231.             rev2=historicalRevision(self, serial)
  232.         else:
  233.             rev2=self
  234.  
  235.         return self.manage_historyCompare(rev1, rev2, REQUEST)
  236.         
  237. Globals.default__class_init__(Historical)
  238.  
  239. def dump(tag, x, lo, hi, r):
  240.     r1=[]
  241.     r2=[]
  242.     for i in xrange(lo, hi):
  243.         r1.append(tag)
  244.         r2.append(x[i])
  245.     r.append("<tr>\n"
  246.             "<td><pre>\n%s\n</pre></td>\n"
  247.             "<td><pre>\n%s\n</pre></td>\n"
  248.             "</tr>\n"
  249.             % (join(r1,'\n'), html_quote(join(r2, '\n'))))
  250.  
  251. def replace(x, xlo, xhi, y, ylo, yhi, r):
  252.  
  253.     rx1=[]
  254.     rx2=[]
  255.     for i in xrange(xlo, xhi):
  256.         rx1.append('-')
  257.         rx2.append(x[i])
  258.  
  259.     ry1=[]
  260.     ry2=[]
  261.     for i in xrange(ylo, yhi):
  262.         ry1.append('+')
  263.         ry2.append(y[i])
  264.  
  265.  
  266.     r.append("<tr>\n"
  267.             "<td><pre>\n%s\n%s\n</pre></td>\n"
  268.             "<td><pre>\n%s\n%s\n</pre></td>\n"
  269.             "</tr>\n"
  270.             % (join(rx1, '\n'), join(ry1, '\n'),
  271.                html_quote(join(rx2, '\n')), html_quote(join(ry2, '\n'))))
  272.  
  273. def html_diff(s1, s2):
  274.     a=split(s1,'\n')
  275.     b=split(s2,'\n')
  276.     cruncher=ndiff.SequenceMatcher(isjunk=split, a=a, b=b)
  277.  
  278.     r=['<table border=1>']
  279.     for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
  280.         if tag == 'replace':
  281.             replace(a, alo, ahi, b, blo, bhi, r)
  282.         elif tag == 'delete':
  283.             dump('-', a, alo, ahi, r)
  284.         elif tag == 'insert':
  285.             dump('+', b, blo, bhi, r)
  286.         elif tag == 'equal':
  287.             dump(' ', a, alo, ahi, r)
  288.         else:
  289.             raise ValueError, 'unknown tag ' + `tag`
  290.     r.append('</table>')
  291.  
  292.     return join(r, '\n')
  293.